package org.example.nlp;

import com.alibaba.excel.EasyExcel;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;
import org.example.ArticleData;
import java.util.*;
import java.util.regex.*;

public class SentimentAnalysis {
    // 全局保存积极和消极词汇
    private static Set<String> positiveWords = new HashSet<>();
    private static Set<String> negativeWords = new HashSet<>();

    public static void main(String[] args) {
        // 1️⃣ 从 Excel 文件加载金融情感词典
        String dictFilePath = "中文金融情感词典_姜富伟等(2020).xlsx";
        loadFinancialDictionaryFromExcel(dictFilePath);

        // 2️⃣ 读取新闻 Excel 数据
        String newsFilePath = "新闻数据_20250207_162924.xlsx";
        List<ArticleData> articles = EasyExcel.read(newsFilePath)
                .head(ArticleData.class)
                .sheet(0)
                .doReadSync();


        // 3️⃣ 初始化 Stanford CoreNLP
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

        // 4️⃣ 遍历文章，分析包含 "比亚迪" 的句子
        Pattern pattern = Pattern.compile("([^。]*比亚迪[^。]*。)");
        for (ArticleData article : articles) {
            Matcher matcher = pattern.matcher(article.getContent());
            while (matcher.find()) {
                String sentence = matcher.group();
                String sentiment = analyzeSentiment(sentence, pipeline);
                String adjustedSentiment = adjustSentimentWithDictionary(sentence, sentiment);

                System.out.println("句子：" + sentence);
                System.out.println("原始情感：" + sentiment);
                System.out.println("修正后情感：" + adjustedSentiment);
            }
        }
    }

    // 5️⃣ 使用 Stanford CoreNLP 进行情感分析
    private static String analyzeSentiment(String sentence, StanfordCoreNLP pipeline) {
        Annotation annotation = new Annotation(sentence);
        pipeline.annotate(annotation);

        for (CoreMap sentenceAnnotation : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
            return sentenceAnnotation.get(SentimentCoreAnnotations.SentimentClass.class);
        }
        return "Neutral"; // 默认返回中性
    }

    // 6️⃣ 结合金融情感词典进行情感修正
    private static String adjustSentimentWithDictionary(String sentence, String originalSentiment) {
        int positiveCount = 0, negativeCount = 0;
        // 简单按照空白分词（若有需要可先进行分词处理）
        String[] words = sentence.split("\\s+");
        for (String word : words) {
            String lowerWord = word.toLowerCase();
            if (positiveWords.contains(lowerWord)) {
                positiveCount++;
            }
            if (negativeWords.contains(lowerWord)) {
                negativeCount++;
            }
        }
        if (positiveCount > negativeCount) return "Positive";
        if (negativeCount > positiveCount) return "Negative";
        return originalSentiment;
    }

    // 7️⃣ 从 Excel 加载金融情感词典（sheet2：消极词语，sheet3：积极词语）
    private static void loadFinancialDictionaryFromExcel(String filePath) {
        // 加载消极词汇（sheet2，索引为1）
        List<DictionaryEntry> negativeEntries = EasyExcel.read(filePath)
                .head(DictionaryEntry.class)
                .sheet(1)
                .doReadSync();
        for (DictionaryEntry entry : negativeEntries) {
            if (entry.getWord() != null && !entry.getWord().trim().isEmpty()) {
                negativeWords.add(entry.getWord().trim().toLowerCase());
            }
        }

        // 加载积极词汇（sheet3，索引为2
        List<DictionaryEntry> positiveEntries = EasyExcel.read(filePath)
                .head(DictionaryEntry.class)
                .sheet(2)
                .doReadSync();
        for (DictionaryEntry entry : positiveEntries) {
            if (entry.getWord() != null && !entry.getWord().trim().isEmpty()) {
                positiveWords.add(entry.getWord().trim().toLowerCase());
            }
        }
    }
}
